package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.pojo.PlannerResult;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    private static final String file_path = System.getProperty("user.dir")+"/file/";
    private static final String http = "http://localhost:8080/file/";

    private  static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @GetMapping("/upload")
    public PlannerResult<String> uploadFile() {
        return PlannerResult.success("Please Upload File");
    }

    @PostMapping("/upload")
    public PlannerResult<String> uploadFile(MultipartFile file) {
        synchronized (FileController.class){
            String flag = System.currentTimeMillis()+"";
            String fileName = file.getOriginalFilename();
            try {
                if(!FileUtil.isDirectory(file_path)){
                    FileUtil.mkdir(file_path);
                }
                FileUtil.writeBytes(file.getBytes(),file_path+flag+"-"+fileName);
                System.out.println("文件上传成功："+fileName);
                logger.info("[Upload]  文件 {} 上传成功", fileName);
                Thread.sleep(1L);
            } catch (Exception e) {
                logger.error("[Upload] 文件 {} 上传失败,原因: " , fileName, e);
                return  PlannerResult.error("文件上传失败"+e);
            }
            return PlannerResult.success(http+flag+"-"+fileName);
        }
    }

    @GetMapping("/{flag}")
    public void downloadFile(@PathVariable String flag, HttpServletResponse response) {
        if(!FileUtil.isDirectory(file_path)){
            FileUtil.mkdir(file_path);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(file_path);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if(StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(file_path+fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                logger.info("[Download]  文件 {} 上传成功", fileName);
            }
        }catch (Exception e){
            logger.error("[Download] 文件 {} 下载失败原因: " ,flag, e);
        }
    }
}
